package com.kun.kunkunmall.order.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.kun.common.OrderConstant;
import com.kun.common.exception.NoStockException;
import com.kun.common.to.OrderTo;
import com.kun.common.to.SeckillOrderTo;
import com.kun.common.to.SkuHasStockVo;
import com.kun.common.utils.R;
import com.kun.common.vo.MemberRespVo;
import com.kun.kunkunmall.order.dao.OrderItemDao;
import com.kun.kunkunmall.order.entity.OrderItemEntity;
import com.kun.kunkunmall.order.entity.PaymentInfoEntity;
import com.kun.kunkunmall.order.enume.OrderStatusEnum;
import com.kun.kunkunmall.order.feign.CartFeignService;
import com.kun.kunkunmall.order.feign.MemberFeignService;
import com.kun.kunkunmall.order.feign.ProductFeignService;
import com.kun.kunkunmall.order.feign.WmsFeignService;
import com.kun.kunkunmall.order.interceptor.OrderLoginUserInterceptor;
import com.kun.kunkunmall.order.service.OrderItemService;
import com.kun.kunkunmall.order.service.PaymentInfoService;
import com.kun.kunkunmall.order.to.OrderCreateTo;
import com.kun.kunkunmall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.utils.PageUtils;
import com.kun.common.utils.Query;

import com.kun.kunkunmall.order.dao.OrderDao;
import com.kun.kunkunmall.order.entity.OrderEntity;
import com.kun.kunkunmall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = OrderLoginUserInterceptor.loginUser.get();
        // 异步进行feign调用请求的上下文丢失问题
        // 应为多线程异步执行没有办法共享threadlocal里面的数据，requestHolder里面使用threadlocal来存储数据
        // 获取源请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 1. 远程查询所有的收货地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        }, threadPoolExecutor);


        CompletableFuture<Void> getCartItemsTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 2. 远程查询购物车所有选中的购物项
            List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
            orderConfirmVo.setItems(currentUserCartItem);
        }, threadPoolExecutor).thenRunAsync(() -> {
            // 拿到结算页面的所有购物项
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            // 远程查询商品是否有库存
            R skusHasStock = wmsFeignService.getSkusHasStock(collect);
            if (skusHasStock.getCode() == 0) {
                List<SKuStockVo> stockData = skusHasStock.getData(new TypeReference<List<SKuStockVo>>() {
                });
                if (stockData != null) {
                    Map<Long, Boolean> map = stockData.stream().collect(Collectors.toMap(SKuStockVo::getSkuId, SKuStockVo::getHasStock));
                    orderConfirmVo.setStocks(map);
                }
            }

        }, threadPoolExecutor);

        // 3.查询用户积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        // 防重令牌
        String token = UUID.randomUUID().toString().replace("_", "");
        orderConfirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(getAddressTask, getCartItemsTask).get();
        return orderConfirmVo;
    }


    //    @GlobalTransactional
    @Transactional
    @Override
    public SubmitRespVo submitOrder(OrderSubmitVo submitVo) {
        SubmitRespVo respVo = new SubmitRespVo();
        MemberRespVo memberRespVo = OrderLoginUserInterceptor.loginUser.get();
        respVo.setCode(0);
        submitVoThreadLocal.set(submitVo);
        // 1. 验证令牌是否合法[令牌的验证和删除必须保证原子性](0 失败，1 成功)
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = submitVo.getOrderToken();
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if (result != null && result == 1L) {
            // 令牌验证删除成功
            // 1. 创建订单
            OrderCreateTo order = createOrder();
            // 2. 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = submitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 3. TODO 保存订单
                saveOrder(order);
                // 4. 库存锁定，只要有异常就回滚订单数据
                // 4.1 封装库存锁定需要的信息
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                // 4.1 锁定库存
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    // 库存锁定成功
                    respVo.setOrder(order.getOrder());
                    // TODO 订单创建成功今后发送消息到RabbitMQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return respVo;
                } else {
                    // 库存锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                respVo.setCode(2); // 验s失败
                return respVo;
            }

        } else {
            // 令牌验证删除失败
            respVo.setCode(1);
            return respVo;
        }
    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        OrderEntity entity = this.query().eq("order_sn", orderSn).one();
        return entity;
    }

    /**
     * 关闭订单
     *
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (Objects.equals(orderEntity.getStatus(), OrderStatusEnum.CREATE_NEW.getCode())) {
            // 订单为待付款状态，关闭订单
            boolean b = this.update().eq("id", entity.getId()).set("status", OrderStatusEnum.CANCLED.getCode()).update();
            // 如果订单解锁成功，发消息通知MQ
            if (b) {
                OrderTo orderTo = new OrderTo();
                BeanUtils.copyProperties(orderEntity, orderTo);
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            }
        }
    }

    /**
     * 封装订单支付所需要的信息并返回
     *
     * @param orderSn 订单号
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity entity = this.getOrderStatus(orderSn);

        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));

        if (list != null && list.size() > 0) {
            payVo.setSubject(list.get(0).getSkuName());
        }

        // 支付需要的金额精确到小数点后面两位
        BigDecimal payAmount = entity.getPayAmount().setScale(2, RoundingMode.UP);
        payVo.setTotal_amount(payAmount.toString());

        payVo.setOut_trade_no(orderSn);
        payVo.setBody(list.get(0).getSkuAttrsVals());

        return payVo;
    }

    @Override
    public PageUtils listWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = OrderLoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> orderEntityList = page.getRecords().stream().peek(order -> {
            // 查询订单里面的所有订单项
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItems(itemEntities);
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);
        return new PageUtils(page);
    }

    /**
     * 根据支付宝传递过来的支付结果，去修改订单状态
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 保存交易流水信息
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCreateTime(vo.getNotify_time());
        paymentInfoEntity.setTotalAmount(new BigDecimal(vo.getTotal_amount()));

        paymentInfoService.save(paymentInfoEntity);

        // 修改订单的状态信息
        String trade_status = vo.getTrade_status();
        if (trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED")) {
            // 支付成功
            String trade_no = vo.getTrade_no();
            this.update().set("status",OrderStatusEnum.PAYED).eq("order_sn",trade_no).update();
        }
        // 验签

        return null;
    }

    /**
     * 创建秒杀订单
     * @param seckillOrderTo
     */
    @Override
    public void createOrderSeckillOrder(SeckillOrderTo seckillOrderTo) {
        // TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setPayAmount(seckillOrderTo.getSeckillPrice().multiply(BigDecimal.valueOf(seckillOrderTo.getNum())));
        this.save(orderEntity);

        // 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setSkuId(seckillOrderTo.getSkuId());
        orderItemEntity.setRealAmount(seckillOrderTo.getSeckillPrice());
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());

        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }


    /**
     * 创建订单方法
     *
     * @return 返回订单信息
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 1. 生成一个订单号
        String orderSn = IdWorker.getTimeId();
        // 1.1 构建订单实体类
        OrderEntity orderEntity = buildOrder(orderSn);
        // 2. 构建所有订单项信息
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);
        // 3. 设置订单的价格积分信息
        computePrice(orderEntity, orderItems);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItems);

        return orderCreateTo;
    }

    /**
     * 设置订单的价格积分信息
     *
     * @param orderEntity
     * @param orderItems
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal giftIntegration = new BigDecimal("0.0");
        BigDecimal giftGrowth = new BigDecimal("0.0");
        for (OrderItemEntity orderItem : orderItems) {
            // 计算订单的总额
            BigDecimal realAmount = orderItem.getRealAmount();
            total = total.add(realAmount);

            BigDecimal promotionAmount = orderItem.getPromotionAmount();
            promotion = promotion.add(promotionAmount);

            BigDecimal couponAmount = orderItem.getCouponAmount();
            coupon = coupon.add(couponAmount);

            BigDecimal integrationAmount = orderItem.getIntegrationAmount();
            integration = integration.add(integrationAmount);

            giftIntegration = giftIntegration.add(BigDecimal.valueOf(orderItem.getGiftIntegration()));

            giftGrowth = giftGrowth.add(BigDecimal.valueOf(orderItem.getGiftGrowth()));

        }
        orderEntity.setTotalAmount(total);
        // 应付总额（需要加上运费）
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);

        orderEntity.setIntegration(giftIntegration.intValue());
        orderEntity.setGrowth(giftGrowth.intValue());
    }

    /**
     * 构建订单实体类
     *
     * @param orderSn 订单号
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        MemberRespVo memberRespVo = OrderLoginUserInterceptor.loginUser.get();
        orderEntity.setMemberId(memberRespVo.getId());
        // 2. 获取收货地址信息
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        R r = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        if (r.getCode() == 0) {
            // 远程查询地址和邮费成功
            FareRespVo data = r.getData(new TypeReference<FareRespVo>() {
            });
            orderEntity.setFreightAmount(data.getFare());
            orderEntity.setReceiverCity(data.getAddressVo().getCity());
            orderEntity.setReceiverDetailAddress(data.getAddressVo().getDetailAddress());
            // 设置收货人信息
            orderEntity.setReceiverName(data.getAddressVo().getName());
            orderEntity.setReceiverPhone(data.getAddressVo().getPhone());
            orderEntity.setReceiverPostCode(data.getAddressVo().getPostCode());
            orderEntity.setReceiverProvince(data.getAddressVo().getProvince());
            orderEntity.setReceiverRegion(data.getAddressVo().getRegion());
        }
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setDeleteStatus(0); // 未删除
        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     *
     * @param
     * @return 所有订单项List<OrderItemEntity>
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        if (currentUserCartItem != null && currentUserCartItem.size() > 0) {
            List<OrderItemEntity> orderItemEntities = currentUserCartItem.stream().map(cartItem -> {
                OrderItemEntity orderItem = buildOrderItem(cartItem);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return orderItemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     *
     * @param cartItem 购物车里面的订单项
     * @return 订单项实体类
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1. 订单信息（订单号）（上面已完成）
        // 2，商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        if (r.getCode() == 0) {
            // 远程查询商品的spu信息成功
            SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
            });
            orderItemEntity.setSpuId(data.getId());
            orderItemEntity.setSpuBrand(data.getBrandId().toString());
            orderItemEntity.setSpuName(data.getSpuName());
            orderItemEntity.setCategoryId(data.getCatalogId());
        }

        // 3. 商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        // 4. 优惠信息【不做】
        // 5. 积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(BigDecimal.valueOf(cartItem.getCount())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(BigDecimal.valueOf(cartItem.getCount())).intValue());

        // 6. 订单项的价格信息（总金额-各种优惠）
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(BigDecimal.valueOf(orderItemEntity.getSkuQuantity()));
        BigDecimal realPrice = originPrice
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realPrice);
        return orderItemEntity;
    }

}